package com.example.weather;

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.weather.model.Constants;
import com.example.weather.model.DailyResponse;
import com.example.weather.model.PlaceResponse;
import com.example.weather.model.RealtimeResponse;
import com.example.weather.model.SkyUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class WeatherActivity extends AppCompatActivity {

    private PlaceResponse.Place place;
    private final Gson gson = new Gson();
    private final SkyUtils skyUtils = new SkyUtils();
    private TextView placeName, currentTemp, currentSky, currentAQI,
            coldRiskText, dressingText, ultravioletText, carWashingText;
    private RelativeLayout nowLayout;
    private LinearLayout forecastLayout;
    private SwipeRefreshLayout refreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        //获取从上个界面传过来的数据
        String dataJson = getIntent().getStringExtra(Constants.WEATHER);
        place = gson.fromJson(dataJson, PlaceResponse.Place.class);

        //初始化控件
        refreshLayout = findViewById(R.id.swipeRefresh);
        placeName = findViewById(R.id.placeName);
        currentTemp = findViewById(R.id.currentTemp);
        currentSky = findViewById(R.id.currentSky);
        currentAQI = findViewById(R.id.currentAQI);
        coldRiskText = findViewById(R.id.coldRiskText);
        dressingText = findViewById(R.id.dressingText);
        ultravioletText = findViewById(R.id.ultravioletText);
        carWashingText = findViewById(R.id.carWashingText);
        nowLayout = findViewById(R.id.nowLayout);
        forecastLayout = findViewById(R.id.forecastLayout);
        Button back = findViewById(R.id.navBtn);
        skyUtils.init();

        refreshLayout.setRefreshing(true);

        //设置刷新事件
        refreshLayout.setOnRefreshListener(() -> {
            requestRealtime();
            requestDaily();

        });
        requestRealtime();
        requestDaily();

        //设置返回的点击事件
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(WeatherActivity.this, MainActivity.class));
                finish();
            }
        });
    }

    //请求天气情况
    private void requestRealtime() {
        OkGo.<String>get(Constants.getRealtimeWeather(place.getLocation()))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //解析数据
                        RealtimeResponse realtimeResponse = gson.fromJson(response.body(), RealtimeResponse.class);
                        //判断是否请求成功
                        if (realtimeResponse.getStatus().equals("ok")) {
                            updateRealtime(realtimeResponse);
                            refreshLayout.setRefreshing(false);
                        } else
                            Toast.makeText(WeatherActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    //请求生活指数
    private void requestDaily() {
        OkGo.<String>get(Constants.getDailyWeather(place.getLocation()))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //解析数据
                        DailyResponse dailyResponse = gson.fromJson(response.body(), DailyResponse.class);
                        //判断是否请求成功
                        if (dailyResponse.getStatus().equals("ok")) {
                            updateDaily(dailyResponse);
                        } else
                            Toast.makeText(WeatherActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void updateDaily(DailyResponse dailyResponse) {
        forecastLayout.removeAllViews();
        DailyResponse.Daily daily = dailyResponse.getResult().getDaily();
        //获取要显示多少条数据
        int days = daily.getSkycon().size();
        for (int i = 0; i < days; i++) {
            DailyResponse.Skycon skycon = daily.getSkycon().get(i);
            DailyResponse.Temperature temperature = daily.getTemperature().get(i);
            //动态添加view
            final View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false);
            //实例化控件
            TextView dataInfo = view.findViewById(R.id.dateInfo);
            ImageView skyIcon = view.findViewById(R.id.skyIcon);
            TextView skyInfo = view.findViewById(R.id.skyInfo);
            TextView temperatureInfo = view.findViewById(R.id.temperatureInfo);
            if (skycon.getDate() != null) {
                try {
                    //格式化时间
                    SimpleDateFormat simpleDataFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                    Date date = simpleDataFormat.parse(skycon.getDate());
                    if (date != null) dataInfo.setText(simpleDataFormat.format(date));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            //绑定数据
            SkyUtils.Sky sky = skyUtils.filterSky(skycon.getValue());
            skyIcon.setImageResource(sky.getIcon());
            skyInfo.setText(sky.getInfo());
            temperatureInfo.setText(getString(R.string.temp, temperature.getMin().toString(), temperature.getMax().toString()));
            forecastLayout.addView(view);
        }

        //填充life_index.xml布局中的数据
        DailyResponse.LifeIndex lifeIndex = daily.getLifeIndex();
        coldRiskText.setText(lifeIndex.getColdRisk().get(0).getDesc());
        dressingText.setText(lifeIndex.getDressing().get(0).getDesc());
        ultravioletText.setText(lifeIndex.getUltraviolet().get(0).getDesc());
        carWashingText.setText(lifeIndex.getCarWashing().get(0).getDesc());
    }

    //更新realtime部分数据
    private void updateRealtime(RealtimeResponse realtimeResponse) {
        RealtimeResponse.RealTime realtime = realtimeResponse.getResult().getRealtime();
        placeName.setText(place.getName());
        String currentTempText = realtimeResponse.getResult().getRealtime().getTemperature() + "℃";
        currentTemp.setText(currentTempText);
        //根据skycon数据获取对应的背景和图标以及天气情况信息
        currentSky.setText(skyUtils.filterSky(realtime.getSkycon()).getInfo());
        currentAQI.setText(getString(R.string.aqi, realtime.getAirQuality().getAqi().getChn().toString()));
        nowLayout.setBackgroundResource(skyUtils.filterSky(realtime.getSkycon()).getBg());
    }
}